package com.proton.carepatchtemp.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.SystemClock;

import com.android.volley.VolleyError;
import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.pair.ParamPair;
import com.proton.carepatchtemp.utils.net.pair.ResultPair;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Api on 2016/9/21.
 */

public class NetUtils {
    //判断有网络
    public static boolean noNet() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager)
                VCare.get().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null == mConnectivityManager) {
            //防止不在主线程中调用时奔溃
            try {
                TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
            } catch (Exception e) {
                LogUtils.e(e);
                return true;
            }
            return true;
        } else {
            NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
            if (null != info) {
                return !info.isAvailable();
            }
        }
//        TastyToast.makeText(VCare.get(),VCare.get().getString(R.string.have_no_netconnect), TastyToast.LENGTH_SHORT, TastyToast.CONFUSING);
        return true;
    }

    public static String getUrlWithParams(String url, List params) {
        StringBuilder sB = new StringBuilder(url);
        if (null != params) {
            int len = params.size();
            if (len > 0) {
                for (int i = 0; i < len; i++) {
                    ParamPair pair = (ParamPair) params.get(i);
                    if (i == 0) {
                        sB.append("?");
                    } else {
                        sB.append("&");
                    }
                    sB.append(pair.getName());
                    sB.append("=");
                    sB.append(pair.getValue());
                }
                sB.append("&");
                sB.append("build");
                sB.append("=");
                sB.append(String.valueOf(VCare.get().localVersion));
            } else {
                sB.append("?");
                sB.append("build");
                sB.append("=");
                sB.append(String.valueOf(VCare.get().localVersion));
            }
        }
        return sB.toString();
    }

    public static void dealVolleyError(VolleyError error, String url, List listA) {
        dealVolleyError(error, url, listA, Codes.NET_TIMEOUT);
    }

    public static void dealVolleyError(VolleyError error, String url, List listA, int code) {
        List list = new ArrayList();
        list.add("volley");
        try {
            list.add(error);
            list.add(error.getLocalizedMessage());
            list.add(error.getMessage());
        } catch (Throwable e) {

        }
        list.add(url);
        list.addAll(listA);
        try {
            list.add(new String(error.networkResponse.data, Extras.CHARSET));
        } catch (UnsupportedEncodingException e) {
            LogUtils.e(e);
        } catch (Throwable e) {
        }
        try {
            // TODO: 2016/9/22 ITBaseActivity
           /* if(VCare.get().currentPage != null && VCare.get().currentPage.get()!=null && VCare.get().currentPage.get() instanceof ITBaseActivity) {
                ITBaseActivity itBaseActivity = (ITBaseActivity) VCare.get().currentPage.get();
                itBaseActivity.dealTimeout();
            }*/
        } catch (Throwable e) {
            LogUtils.e(e);
        }
        LogUtils.e(list);
        new MainEvent(code, Extras.RET_F, R.string.no_net).post();
    }

    public static void dealNeedLogin() {
        EventBus.getDefault().post(new MainEvent(Codes.NET_NEED_RELOGIN));
        SystemClock.sleep(200);
        VCare.get().dealNeedLogin(false);
    }

    public static ResultPair decodeResult(JSONObject response) {
        ResultPair resultPair = new ResultPair();
        resultPair.setName(Extras.RET_F);
        try {
            resultPair.setValue(response.getString(Extras.DATA));
        } catch (JSONException e) {
        }
        try {
            resultPair.setName(response.getString(Extras.RET));
        } catch (JSONException e) {
        }
        return resultPair;
    }

    public static int getNet() {
        ConnectivityManager connectivity = (ConnectivityManager) VCare.get()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return ConnectivityManager.TYPE_DUMMY;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetworkInfo netWorkInfo = info[i];
                        if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return ConnectivityManager.TYPE_WIFI;
//                            return ConnectivityManager.TYPE_MOBILE;
                        } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            return ConnectivityManager.TYPE_MOBILE;
                        }
                    }
                }
            }
        }
        return ConnectivityManager.TYPE_DUMMY;
    }

    public static boolean hasNet() {
        return !noNet();
    }
}
